package com.fishy.chat.initializer;

import com.fishy.chat.codec.WebSocketMessageEncoder;
import com.fishy.chat.handler.WebSocketChatHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ChannelHandler.Sharable
public class HttpAndWebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Resource
    private WebSocketChatHandler webSocketChatHandler;
    @Resource
    private WebSocketMessageEncoder webSocketMessageEncoder;

    @Override
    protected void initChannel(SocketChannel ch){
        ch.pipeline()
                .addLast(new HttpServerCodec())
                .addLast(new ChunkedWriteHandler())
                .addLast(new HttpObjectAggregator(65536))
                .addLast(new WebSocketServerProtocolHandler("/chat", null, true))
                .addLast(new WebSocketServerCompressionHandler())
                .addLast(webSocketMessageEncoder)
                .addLast(webSocketChatHandler);
    }

}
